/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 搜索历史组件 - 显示搜索历史和热门搜索
 * 迁移自原始项目的 SearchHistoryWidget，适配新的 MVVM 架构
 */

import 'package:flutter/material.dart';
import '../../viewmodels/music_search_view_model.dart';

/// 搜索历史组件
/// 纯展示型组件，所有数据通过props传入，支持高度自定义
class SearchHistoryWidget extends StatelessWidget {
  const SearchHistoryWidget({
    super.key,
    required this.historyItems,
    required this.hotItems,
    this.historyTitle = '历史搜索',
    this.hotTitle = '热门搜索',
    this.showHistory = true,
    this.showHot = true,
    this.onClearHistory,
    this.onItemTap,
    this.maxHistoryItems = 10,
    this.maxHotItems = 20,
    this.itemSpacing = 8.0,
    this.sectionSpacing = 24.0,
    this.historyTitleStyle,
    this.hotTitleStyle,
    this.itemTextStyle,
    this.itemBackgroundColor,
    this.itemBorderRadius = 16.0,
    this.itemPadding = const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
  });

  /// 历史搜索数据列表
  final List<SearchItem> historyItems;

  /// 热门搜索数据列表
  final List<SearchItem> hotItems;

  /// 历史搜索标题文本
  final String historyTitle;

  /// 热门搜索标题文本
  final String hotTitle;

  /// 是否显示历史搜索区块
  final bool showHistory;

  /// 是否显示热门搜索区块
  final bool showHot;

  /// 清空历史搜索回调
  final VoidCallback? onClearHistory;

  /// 搜索项点击回调
  final Function(SearchItem item)? onItemTap;

  /// 最大历史搜索项数量
  final int maxHistoryItems;

  /// 最大热门搜索项数量
  final int maxHotItems;

  /// 搜索项之间的间距
  final double itemSpacing;

  /// 区块之间的间距
  final double sectionSpacing;

  /// 历史搜索标题样式
  final TextStyle? historyTitleStyle;

  /// 热门搜索标题样式
  final TextStyle? hotTitleStyle;

  /// 搜索项文本样式
  final TextStyle? itemTextStyle;

  /// 搜索项背景颜色
  final Color? itemBackgroundColor;

  /// 搜索项圆角半径
  final double itemBorderRadius;

  /// 搜索项内边距
  final EdgeInsets itemPadding;

  @override
  Widget build(BuildContext context) {
    final List<Widget> sections = [];

    // 构建历史搜索区块
    if (showHistory && historyItems.isNotEmpty) {
      sections.add(_buildHistorySection(context));
    }

    // 构建热门搜索区块
    if (showHot && hotItems.isNotEmpty) {
      sections.add(_buildHotSection(context));
    }

    if (sections.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: sections
          .expand((section) => [section, SizedBox(height: sectionSpacing)])
          .take(sections.length * 2 - 1)
          .toList(),
    );
  }

  /// 构建历史搜索区块
  Widget _buildHistorySection(BuildContext context) {
    final displayItems = historyItems.take(maxHistoryItems).toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionHeader(
          context,
          title: historyTitle,
          titleStyle: historyTitleStyle,
          showClearButton: onClearHistory != null,
          onClear: onClearHistory,
        ),
        const SizedBox(height: 12),
        _buildItemsWrap(
          context,
          items: displayItems,
          showIcon: true,
          icon: Icons.history,
        ),
      ],
    );
  }

  /// 构建热门搜索区块
  Widget _buildHotSection(BuildContext context) {
    final displayItems = hotItems.take(maxHotItems).toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionHeader(
          context,
          title: hotTitle,
          titleStyle: hotTitleStyle,
          showClearButton: false,
        ),
        const SizedBox(height: 12),
        _buildItemsWrap(
          context,
          items: displayItems,
          showIcon: false,
        ),
      ],
    );
  }

  /// 构建区块标题头部
  Widget _buildSectionHeader(
    BuildContext context, {
    required String title,
    TextStyle? titleStyle,
    bool showClearButton = false,
    VoidCallback? onClear,
  }) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: titleStyle ??
              const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
        ),
        if (showClearButton && onClear != null)
          InkWell(
            onTap: onClear,
            borderRadius: BorderRadius.circular(4),
            child: const Padding(
              padding: EdgeInsets.all(4),
              child: Icon(
                Icons.clear_all,
                size: 18,
                color: Colors.grey,
              ),
            ),
          ),
      ],
    );
  }

  /// 构建搜索项流式布局
  Widget _buildItemsWrap(
    BuildContext context, {
    required List<SearchItem> items,
    bool showIcon = false,
    IconData? icon,
  }) {
    return Wrap(
      spacing: itemSpacing,
      runSpacing: itemSpacing,
      children: items
          .asMap()
          .entries
          .map((entry) => _buildSearchItem(
                context,
                entry.value,
                entry.key,
                showIcon: showIcon,
                icon: icon,
              ))
          .toList(),
    );
  }

  /// 构建搜索项
  Widget _buildSearchItem(
    BuildContext context,
    SearchItem item,
    int index, {
    bool showIcon = false,
    IconData? icon,
  }) {
    return InkWell(
      onTap: () => onItemTap?.call(item),
      borderRadius: BorderRadius.circular(itemBorderRadius),
      child: Container(
        padding: itemPadding,
        decoration: BoxDecoration(
          color: itemBackgroundColor ?? Colors.grey.shade100,
          borderRadius: BorderRadius.circular(itemBorderRadius),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (showIcon && icon != null) ...[
              Icon(
                icon,
                size: 14,
                color: Colors.grey.shade600,
              ),
              const SizedBox(width: 4),
            ],
            Flexible(
              child: Text(
                item.text,
                style: itemTextStyle ??
                    const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Colors.black87,
                    ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            if (item.subtitle != null) ...[
              const SizedBox(width: 4),
              Text(
                item.subtitle!,
                style: const TextStyle(
                  fontSize: 12,
                  color: Colors.grey,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 搜索历史管理器工具类
class SearchHistoryManager {
  /// 将字符串列表转换为SearchItem列表
  static List<SearchItem> fromStringList(List<String> strings) {
    return strings.map((text) => SearchItem(text: text)).toList();
  }

  /// 创建带副标题的搜索项列表
  static List<SearchItem> fromMapList(
    List<Map<String, dynamic>> maps, {
    String textKey = 'text',
    String? subtitleKey,
  }) {
    return maps
        .map((map) => SearchItem(
              text: map[textKey]?.toString() ?? '',
              subtitle:
                  subtitleKey != null ? map[subtitleKey]?.toString() : null,
            ))
        .toList();
  }
}
